<template>
  <div>
    <n-card class="user-content">
      <!-- 搜索部分 -->
      <n-grid x-gap="24">
        <n-gi span="6">
          <n-input-group>
            <n-input :style="{ width: '100%' }" placeholder="请输入资产名/ip" />
            <n-button type="primary" @click="searchDev">搜索</n-button>
          </n-input-group>
        </n-gi>
        <n-gi span="18">
          <n-space>
            <n-button type="primary" @click="addDev">新建资产</n-button>
            <n-button type="default" style="margin-left: 20px">
              <template #icon>
                <n-icon>
                  <CloudUploadSharp />
                </n-icon>
              </template>
              导 入
            </n-button>
          </n-space>
        </n-gi>
      </n-grid>

      <!-- 资产列表 -->
      <div style="margin-top: 30px">
        <n-data-table
          ref="table"
          :columns="columns"
          :data="data"
          :row-key="(row) => row.id"
          @update:checked-row-keys="handleCheck"
        />
      </div>

      <!-- 底部分页全选 -->
      <n-grid x-gap="24" style="margin-top: 15px; margin-bottom: 15px">
        <!-- 全选按钮 -->
        <n-gi span="4">
          <span>已选 {{ checkedRowKeys.length }} 行</span>
        </n-gi>

        <!-- 分页部分 -->
        <n-gi span="20">
          <n-space justify="end">
            <n-pagination
              v-model:page="page"
              v-model:page-size="pageSize"
              :page-count="pageCount"
              show-size-picker
              :page-sizes="pageGroup"
              show-quick-jumper
              @update:page="PageChange"
              @update:page-size="pageSizeChange"
            />
          </n-space>
        </n-gi>
      </n-grid>
    </n-card>

    <!-- 新增资产对话框 -->
    <n-modal
      class="custom-card"
      v-model:show="showModal"
      preset="card"
      style="width: 600px;"
      header-style="height:50px;font-size:20px"
      :title="modalTitle"
      size="huge"
      :bordered="false"
      :segmented="{ content: 'hard' }"
      :mask-closable="false"
    >
      <n-form
        :model="devValue"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="70"
        :style="{
          maxWidth: '640px'
        }"
      >
        <n-form-item label="资产名" path="name">
          <n-input placeholder="资产名" v-model:value="devValue.name" />
        </n-form-item>

        <n-form-item label="IP" path="ip">
          <n-input placeholder="IP" v-model:value="devValue.ip" />
        </n-form-item>

        <n-form-item label="状态" path="status">
          <!-- <n-switch :default-value="true" @update:value="stateChecked"> -->
          <n-switch v-model:value="devValue.status">
            <template #checked>启用</template>
            <template #unchecked>禁用</template>
          </n-switch>
        </n-form-item>

        <n-form-item label="类型" path="type">
          <n-select v-model:value="devValue.type" :options="types" />
        </n-form-item>

        <n-form-item label="协议" path="service">
          <n-select v-model:value="devValue.service" :options="services" />
        </n-form-item>
        <n-form-item label="端口" path="port">
          <n-input-number placeholder="端口号" v-model:value="devValue.port" clearable />
        </n-form-item>

        <n-form-item label="简要说明" path="description">
          <n-input placeholder="简要说明" v-model:value="devValue.description" type="textarea" />
        </n-form-item>

        <n-form-item>
          <n-space justify="end" style="width:100%;">
            <n-button @click="cancleBtn">取消</n-button>
            <n-button type="primary" @click="submitAddDev">确认</n-button>
          </n-space>
        </n-form-item>
      </n-form>
    </n-modal>

    <!-- 账号管理对话框 -->
    <n-modal
      v-model:show="showAccountModal"
      preset="card"
      style="max-width: 600px;"
      header-style="height:50px;font-size:20px"
      :title="accountTitle"
      size="huge"
      :bordered="false"
      :mask-closable="false"
      :segmented="{ content: 'hard' }"
      :content-style="{
        padding: '0'
      }"
    >
      <n-data-table :columns="accountColumns" size="small" :data="accountData" />

      <n-button type="info" style="margin:10px" @click="addAccountBtn">添加账号</n-button>
      <!-- 添加账号弹框 -->
      <n-modal
        style="max-width: 450px;"
        :segmented="{ content: 'hard' }"
        :mask-closable="false"
        v-model:show="addAccountModal"
        header-style="height:50px;font-size:20px"
        size="huge"
        title="账号管理"
        preset="card"
      >
        <n-form
          label-placement="left"
          label-width="60"
          :model="accountFormValue"
          :rules="accountFormRules"
          ref="accountForm"
        >
          <n-form-item label="账号" path="account">
            <n-input v-model:value="accountFormValue.account" placeholder="输入账号名" />
          </n-form-item>

          <n-form-item label="状态" path="status">
            <!-- <n-switch :default-value="true" @update:value="stateChecked"> -->
            <n-switch v-model:value="accountFormValue.status">
              <template #checked>启用</template>
              <template #unchecked>禁用</template>
            </n-switch>
          </n-form-item>

          <n-form-item label="密码" path="password">
            <n-input type="password" placeholder="输入密码" v-model:value="accountFormValue.password" />
          </n-form-item>
          <n-form-item label="验证" path="reenteredPassword">
            <n-input
              type="password"
              placeholder="重新输入密码校验"
              v-model:value="accountFormValue.reenteredPassword"
              :disabled="!accountFormValue.password"
            />
          </n-form-item>
          <n-form-item>
            <n-button @click="submitAccountBtn" type="info">确定</n-button>
          </n-form-item>
        </n-form>
      </n-modal>
    </n-modal>
  </div>
</template>

<script setup>
import { CloudUploadSharp } from "@vicons/ionicons5";
import { useMessage, NBadge, NButton, NSpace, NTag, useDialog } from "naive-ui";
import SvgIcon from '../../components/SvgIcon.vue'
import {
  computed,
  getCurrentInstance,
  onBeforeMount,
  ref,
  h,
} from "vue";
import formateData from "../../utils/formateData";
const { proxy } = getCurrentInstance();

const message = useMessage();
const dialog = useDialog()

// 弹出对话框
const showModal = ref(false)

const modalTitle = ref(null)
const formRef = ref(null)



function devValueInit() {
  return {
    id: null,
    name: "测试",
    ip: "192.168.2.7",
    status: true,
    service: "ssh",
    port: 22,
    account: "",
    type: 1,
    password: "",
    description: "这是一个测试的资产",
    createdAt: null,
    updatedAt: null,
    deletedAt: null
  }
}

const devValue = ref(devValueInit())


//自定义校验事件
function validatePasswordStartWith(rule, value) {
  return (
    devValue.value.password &&
    devValue.value.password.startsWith(value) &&
    devValue.value.password.length >= value.length
  )
}
function validatePasswordSame(rule, value) {
  return value === devValue.value.password
}

const rules = {
  name: [
    { required: true, type: 'string', trigger: 'blur', message: '不能输入空值,最短长度为 2', min: 2 }
  ],
  ip: [
    { required: true, type: 'string', trigger: 'blur', message: '不能输入空值' }
  ],
  port: [
    { required: true, type: 'number', trigger: 'blur', message: '请输入1-65535之间的值', min: 1, max: 65535 }
  ],
}

// 添加用户函数
function addDev() {
  devValue.value = devValueInit()
  showModal.value = true
  modalTitle.value = '新建资产'

}

function cancleBtn() {
  showModal.value = false
  devValue.value = {}
}

function submitAddDev() {
  formRef.value.validate((err) => {
    if (!err) {
      let reqMethod
      let apiAddr

      switch (modalTitle.value) {
        case '新建资产':
          reqMethod = 'POST'
          apiAddr = '/api/dev'

          break;
        case '编辑资产':
          reqMethod = 'PUT'
          apiAddr = '/api/dev/' + devValue.value.id

          break;
        default:
          break;
      }

      console.log(devValue.value)
      proxy.$http({
        method: reqMethod,
        url: apiAddr,
        // data: devValue.value
        data: devValue.value
      })
        .then(function (response) {
          message.destroyAll();
          message.success(response.data.msg, { duration: 2000 })
          // 关闭对话框，刷新页面
          showModal.value = false
          getDevInfo(page.value, pageSize.value)
        })

        .catch(function (error) {
          console.error(error);
          message.destroyAll();
          message.error("请求失败，请查看网络是否连接", { duration: 2000 })
        })


    } else {
      message.error(err);
    }
  })



}



//操作列按钮
const tableBtns = [
  {
    text: "编辑",
    type: "primary",
    click(row) {
      // modalValue.value = toRaw(row)
      // console.log(toRaw(row))
      showModal.value = true
      modalTitle.value = '编辑资产'
      //发起网络请求，获取单个用户详细信息
      proxy.$http.get(`/api/dev/${row.id}`).then(response => {
        console.log(response)
        if (response.status != 200) {
          message.error(response.data.msg)
          return
        }
        devValue.value = response.data.host
      }).catch(err => {
        message.error(err)
      })

    }
  },
  {
    text: "账号",
    type: "default",
    click(row) {
      hostId = row.id
      getAccountList(row.id)
      showAccountModal.value = true
      accountTitle.value = row.name
    }
  },
  {
    text: "删除",
    type: "error",
    click(row) {
      // console.log(row)
      dialog.error({
        title: '删除资产',
        content: '是否删除资产，已删除的资产无法找回！',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          // message.success('我就知道')
          proxy.$http.delete(`/api/dev/${row.id}`).then(response => {
            console.log(response)
            if (response.status != 204) {
              message.error(response.data.msg)
              return
            }
            message.success("删除成功")
            getDevInfo(page.value, pageSize.value)
          }).catch(err => {
            message.error(err)
          })

        },
        onNegativeClick: () => {
          // message.error('不确定')
        }
      })

    },
  },
];
// 协议
const services = ref([
  {
    label: "ssh",
    value: "ssh",
    type: 'info'
  },
  {
    label: "rdp",
    value: "rdp",
    type: 'success',
    disabled: true
  },
  {
    label: "vnc",
    value: "vnc",
    type: 'success',
    disabled: true
  }
])

const types = ref([
  {
    label: "Linux",
    value: 1,
  },
  {
    label: "Windows",
    value: 2,
    disabled: true
  },
  {
    label: "Network",
    value: 3,
    disabled: true
  },
])

//定义表格列
const columns = [
  {
    type: "selection",
  },
  {
    title: "资产名",
    key: "name",
    align: "center"
  },
  {
    title: "IP",
    key: "ip",
    align: "center",
  },
  {
    title: "协议",
    key: "service",
    align: "center",
    render(row) {
      let roleName = ''
      let type = ''
      services.value.map((roleItem) => {
        if (roleItem.value == row.service) {
          roleName = roleItem.label
          type = roleItem.type
        }
      })
      return h("div", null, [
        h(
          NTag,
          {
            type: type,
          },
          { default: () => roleName }
        )
      ]);
    }
  },
  {
    title: "资产类型",
    key: "type",
    align: "center",
    render(row) {
      return h(
        "div",
        {
          justify: "center",
        },
        [
          h(
            SvgIcon,
            {
              style: 'font-size:1.2rem',
              name: 'linux'
            },
            { default: () => roleName }
          ),
          h(
            'span',
            {
              style: 'margin-left:6px'
            },
            { default: () => 'Liunx' }
          )
        ]);
    }
  },

  {
    title: "状态",
    key: "state",
    align: "center",
    render(row) {
      if (row.status == 1) {
        return h("div", null, [
          h(
            NBadge,
            {
              dot: true,
              processing: true,
              type: "success",
              style: "margin-right:5px",
            },
            null
          ),
          "正常",
        ]);
      } else {
        return h("div", null, [
          h(
            NBadge,
            {
              dot: true,
              type: "error",
              style: "margin-right:5px",
            },
            null
          ),
          "禁用",
        ]);
      }
    },
  },
  {
    title: "简要说明",
    key: "description",
    align: "center",
    width: 200,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: "创建时间",
    align: "center",
    render(row) {
      return h(
        'span', null, formateData.formateDate(row.createdAt)
      )
    }
  },

  {
    title: "操作",
    align: "center",
    width: 200,
    render(row) {
      return h(
        NSpace,
        {
          justify: "center",
        },
        {
          default: () =>
            tableBtns.map((tagKey) => {
              return h(
                NButton,
                {
                  type: tagKey.type,
                  size: "small",
                  onClick: () => tagKey.click(row)
                },
                { default: () => tagKey.text }
              );
            }),
        }
      );
    },
  },
];

const data = ref([]);

const checkedRowKeys = ref([]);

// 获取分页用户信息的函数
function getDevInfo(pagenum, pagesize) {
  proxy.$http
    .get("/api/dev/list", {
      params: {
        page: pagenum - 1,
        pagesize: pagesize,
      },
    })
    .then(function (response) {
      console.log(response)
      if (response.status != 200) {
        message.error(response.data.msg);
        return;
      }

      if (response.data.hosts) {
        data.value = response.data.hosts;
      } else {
        data.value = []
      }

      total.value = response.data.total;

      console.log(response.data);
    })
    .catch(function (error) {
      console.log(error);
    });
}

function handleCheck(rowKeys) {
  checkedRowKeys.value = rowKeys;
}

//查询用户
function searchDev() {
  console.log("查询资产");
}

// 分页部分
const page = ref(1);
const pageSize = ref(10);
let total = ref(null);
const pageGroup = [10, 20, 30, 50, 100]

const pageCount = computed(() => {
  return Math.ceil(total.value / pageSize.value);
});

// 翻页回调
function PageChange(p) {
  page.value = p;
  // console.log(p);
  getDevInfo(p, pageSize.value);
}
// 设置吗每页显示数量回调
function pageSizeChange(psize) {
  pageSize.value = psize;
  page.value = 1
  getDevInfo(page.value, psize);
}



// 账号弹窗部分
const showAccountModal = ref(false)
const addAccountModal = ref(false)
const accountTitle = ref("")
const accountData = ref([])
const accountForm = ref(null)
let hostId = 0

//请求方法
let accountRequstMethod




//自定义校验事件
function validatePasswordSameAccount(rule, value) {
  return value === accountFormValue.value.password
}

const accountFormValue = ref({
  account: '',
  status: true,
  password: '',
  reenteredPassword: ''

})



const accountFormRules = {
  account: [{ required: true, type: 'string', trigger: 'blur', message: '不能输入空值,最短长度为 2', min: 2 }],
  password: [
    { type: 'string', trigger: 'blur', message: '最短长度为 5', min: 5 }
  ],
  reenteredPassword: [
    { type: 'string', trigger: 'blur', message: '最短长度为 5', min: 5 },
    { validator: validatePasswordSameAccount, message: '两次密码输入不一致', trigger: ['blur', 'password-input'] }
  ],
}

// 根据资产id获取账号列表
function getAccountList(id) {
  //发起网络请求，获取单个用户详细信息
  proxy.$http.get(`/api/account/${id}`).then(response => {
    console.log(response)
    if (response.status != 200) {
      message.error(response.data.msg)
      return
    }
    accountData.value = response.data.accounts
  }).catch(err => {
    message.error(err)
  })
}

// accountColumns 操作列按钮
const accountColumnsOperate = [
  {
    title: '编辑',
    click(row) {
      // console.log(row)
      accountFormValue.value = {
        account: row.account,
        status: row.status,
        password: '',
        reenteredPassword: '',
        hostId: row.hostId
      }
      addAccountModal.value = true
    }
  },
  {
    title: '删除',
    click(row) {
      dialog.warning({
        title: '警告',
        positiveText: '删除',
        negativeText: '取消',
        content: '账号一旦删除，无法找回！',
        onPositiveClick: () => {
          proxy.$http.delete(`/api/account/${row.id}`).then(res => {
            if (res.status != 204) {
              message.error(res.data.msg)
            } else {
              message.success("删除成功")
            }

            getAccountList(row.hostId)

          }).catch(err => {
            message.error('删除失败！')
          })
        },
      })
    }
  }
]

// const accountData 
const accountColumns = [
  {
    title: "账号",
    key: "account",
    align: "center"
  },
  {
    title: "密码",
    key: "isNull",
    align: "center",
    render(row) {
      if (row.isNull) {
        return h(NTag, {
          type: "success"
        }, {
          default: () => "已托管"
        })
      } else {
        return h(NTag, {
          type: "warning"
        }, {
          default: () => "未托管"
        })
      }
    }
  },
  {
    title: "状态",
    key: "status",
    align: "center",
    render(row) {
      if (row.status) {
        return h("div", null, [
          h(
            NBadge,
            {
              dot: true,
              processing: true,
              type: "success",
              style: "margin-right:5px",
            },
            null
          ),
          "启用",
        ]);
      } else {
        return h("div", null, [
          h(
            NBadge,
            {
              dot: true,
              type: "error",
              style: "margin-right:5px",
            },
            null
          ),
          "禁用",
        ]);
      }
    }
  },
  {
    title: '操作',
    align: "center",
    render(row) {
      return h(
        NSpace,
        {
          justify: "center",
        },
        {
          default: () =>
            accountColumnsOperate.map((tagKey) => {
              return h(
                'span',
                {
                  text: true,
                  onClick: () => tagKey.click(row),
                  style: 'text-decoration: underline;cursor:pointer'
                },
                { default: () => tagKey.title }
              );
            }),
        }
      );
    },
  }

]

// 添加账号按钮
function addAccountBtn() {
  accountFormValue.value = {
    account: '',
    status: true,
    password: '',
    reenteredPassword: '',
    hostId: hostId
  }
  addAccountModal.value = true
}

// 提交账号信息按钮
function submitAccountBtn(e) {
  accountForm.value.validate((errors) => {
    if (!errors) {
      // message.success('验证成功')
      console.log(accountFormValue.value)
      proxy.$http.post("/api/account", accountFormValue.value).then(response => {
        if (response.status == 201) {
          message.success('创建成功')
          addAccountModal.value = false
          getAccountList(hostId)
        } else {
          message.error('创建失败')
        }
      }).catch(err => {
        console.log(error)
        message.error('创建失败')
      })



    }
  })

}

onBeforeMount(() => {
  getDevInfo(page.value, pageSize.value)
})
</script>
